let dpr = window.devicePixelRatio

function main() {
  const canvas = document.createElement('canvas')
  canvas.width = window.innerWidth * dpr
  canvas.height = window.innerHeight * dpr
  document.getElementById('app').appendChild(canvas)
  
  const gl = canvas.getContext('webgl', {
    antialias: true
  })
  if (!gl) {
    console.error('WebGL not supported')
    return
  }

  // 顶点着色器
  const vertexShader = gl.createShader(gl.VERTEX_SHADER)
  gl.shaderSource(vertexShader, `
    attribute vec2 position;
    varying vec2 vPos;
    
    void main() {
      vPos = position;
      gl_Position = vec4(position, 0.0, 1.0);
    }
  `)
  gl.compileShader(vertexShader)

  // 片元着色器
  const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER)
  gl.shaderSource(fragmentShader, `
    precision mediump float;
    varying vec2 vPos;
    uniform float uRadius;

    void main() {
      float dist = length(vPos) / uRadius;
      if(dist > 1.0) discard;
      
      vec3 color1 = vec3(1.0, 0.0, 0.0);  // 红色
      vec3 color2 = vec3(0.0, 0.0, 1.0);  // 蓝色
      vec3 color = mix(color1, color2, dist);
      
      gl_FragColor = vec4(color, 1.0);
    }
  `)
  gl.compileShader(fragmentShader)

  // 创建程序
  const program = gl.createProgram()
  gl.attachShader(program, vertexShader)
  gl.attachShader(program, fragmentShader)
  gl.linkProgram(program)
  gl.useProgram(program)

  const r = 0.7
  // 设置 uniform 变量
  const radiusLoc = gl.getUniformLocation(program, 'uRadius');
  gl.uniform1f(radiusLoc, r);

  // 创建圆形的顶点数据
  const vertices = []
  const segments = 64
  for (let i = 0; i <= segments; i++) {
    const angle = (i / segments) * Math.PI * 2
    vertices.push(r * Math.cos(angle), r * Math.sin(angle))
  }
  vertices.push(0, 0) // 中心点

  // 创建缓冲区
  const vertexBuffer = gl.createBuffer()
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer)
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW)

  // 设置顶点属性
  const positionLoc = gl.getAttribLocation(program, 'position')
  gl.enableVertexAttribArray(positionLoc)
  gl.vertexAttribPointer(positionLoc, 2, gl.FLOAT, false, 0, 0)

  // 渲染
  function render() {
    // 计算视口大小，确保与圆的半径匹配
    const viewportSize = Math.min(canvas.width, canvas.height) / 2;
    const x = (canvas.width - viewportSize) / 2;
    const y = (canvas.height - viewportSize) / 2;
    
    gl.viewport(x, y, viewportSize, viewportSize);
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);
    
    gl.drawArrays(gl.TRIANGLE_FAN, 0, vertices.length / 2); // 使用顶点绘制
    requestAnimationFrame(render);
  }
  render()
}

main()